import json
from rest_framework import serializers
from ..models.Keyword import Keyword

# 查询内容序列化
class KeywordDetailListQuerySerializer(serializers.Serializer):
    k = serializers.CharField(required=False,allow_blank=True)
    v = serializers.CharField(required=False,allow_blank=True)
    kt = serializers.ListField(required=False)

    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "k" in attrs:
            attrs["k"] = attrs["k"].strip()
            if attrs["k"] == "": attrs.pop("k")
        if "v" in attrs:
            attrs["v"] = attrs["v"].strip()
            if attrs["v"] == "": attrs.pop("v")
        if "kt" in attrs:
            if len(attrs["kt"]) == 0: attrs.pop("kt")
        if ("k" not in attrs or attrs["k"] == "") and ("v" not in attrs or attrs["v"] == "") and\
           ("kt" not in attrs or len(attrs["kt"]) == 0):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"关键词的键：", "dataIndex":"k", "type":"CharField"},
                {"title":"关键词键对应的值：", "dataIndex":"v", "type":"CharField"},
                {"title":"关键词类别：", "dataIndex":"kt", "type":"ForeignKey"},]
        
        
# 用于输出查询时的数据
class KeywordDetailListSerializer(serializers.ModelSerializer):
    kt = serializers.SerializerMethodField()

    class Meta:
        model = Keyword
        fields = ['uuid', 'k', 'v', "kt"]
        
    def get_kt(self, obj): # obj: Literature类实例
        if obj.kt is not None:
            return "{}({})".format(obj.kt.zh_name, obj.kt.name) + "\n"
        else:
            return "未知"
      
    @classmethod
    def get_extra_fields_info(self):
        return [{"title":"关键词类别", "dataIndex":"kt", "type":"CharField"},]
    
    
# 查询内容序列化
class TagListQuerySerializer(serializers.Serializer):
    k = serializers.CharField(required=False,allow_blank=True)
    v = serializers.CharField(required=False,allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "k" in attrs:
            attrs["k"] = attrs["k"].strip()
            if attrs["k"] == "": attrs.pop("k")
        if "v" in attrs:
            attrs["v"] = attrs["v"].strip()
            if attrs["v"] == "": attrs.pop("v")
        if ("k" not in attrs or attrs["k"] == "") and ("v" not in attrs or attrs["v"] == ""):
            filter_flag = False
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"标签：", "dataIndex":"k", "type":"CharField"},
                {"title":"中文翻译：", "dataIndex":"v", "type":"CharField"},]
        
        
# 用于输出查询时的数据
class TagListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword
        fields = ['uuid', 'k', 'v']
        
    @classmethod
    def get_extra_fields(self):
        return [{"title":"标签", "dataIndex":"k", "type":"CharField"},
                {"title":"中文翻译", "dataIndex":"v", "type":"CharField"},]
        

# 查询内容序列化
class SubjectListQuerySerializer(serializers.Serializer):
    k = serializers.CharField(required=False,allow_blank=True)
    v = serializers.CharField(required=False,allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "k" in attrs:
            attrs["k"] = attrs["k"].strip()
            if attrs["k"] == "": attrs.pop("k")
        if "v" in attrs:
            attrs["v"] = attrs["v"].strip()
            if attrs["v"] == "": attrs.pop("v")
        if ("k" not in attrs or attrs["k"] == "") and ("v" not in attrs or attrs["v"] == ""):
            filter_flag = False
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"主题：", "dataIndex":"k", "type":"CharField"},
                {"title":"中文翻译：", "dataIndex":"v", "type":"CharField"},]
        
        
# 用于输出查询时的数据
class SubjectListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword
        fields = ['uuid', 'k', 'v']
        
    @classmethod
    def get_extra_fields(self):
        return [{"title":"主题", "dataIndex":"k", "type":"CharField"},
                {"title":"中文翻译", "dataIndex":"v", "type":"CharField"},]
        
        
# 查询内容序列化
class KeywordListQuerySerializer(serializers.Serializer):
    k = serializers.CharField(required=False,allow_blank=True)
    v = serializers.CharField(required=False,allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "k" in attrs:
            attrs["k"] = attrs["k"].strip()
            if attrs["k"] == "": attrs.pop("k")
        if "v" in attrs:
            attrs["v"] = attrs["v"].strip()
            if attrs["v"] == "": attrs.pop("v")
        if ("k" not in attrs or attrs["k"] == "") and ("v" not in attrs or attrs["v"] == ""):
            filter_flag = False
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"关键词：", "dataIndex":"k", "type":"CharField"},
                {"title":"中文翻译：", "dataIndex":"v", "type":"CharField"},]
        
        
# 用于输出查询时的数据
class KeywordListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Keyword
        fields = ['uuid', 'k', 'v']
    
    @classmethod
    def get_extra_fields(self):
        return [{"title":"关键词", "dataIndex":"k", "type":"CharField"},
                {"title":"中文翻译", "dataIndex":"v", "type":"CharField"},]